package com.hzqy.service.commons;

import com.hzqy.commons.service.AuthenticatedService;
import com.hzqy.commons.utils.IpUtil;
import com.hzqy.commons.utils.RedisUtils;
import com.hzqy.persistence.dao.commons.CommonsDao;
import com.hzqy.persistence.dao.hotel.HotelDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class CommonsServiceBean  extends GenericServiceBean<PmsUserVo,CommonsDao, Integer>{

	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private CommonsDao commonsDao;
	@Resource
	private HotelDao hotelDao;

	@Override
	public CommonsDao getEntityDao() {
		return commonsDao;
	}
	public SysProductVo selectProduct(int f_sp_id) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("f_sp_id", f_sp_id);
		return commonsDao.selectProductList(map).get(0);
	}
	
	public SysProductVo selectProductByParentId(int f_sp_id) {
		return commonsDao.selectProductByParentId(f_sp_id);
	}

	public List<SysProductVo> selectProductListByCatalogId(int f_catalog_id) {
		List<SysProductVo> productList = commonsDao.selectProductListByCatalogId(f_catalog_id);
		return productList;
	}
	public List<SysProductVo> selectProductListByProductId(int f_sp_id) {
		List<SysProductVo> productList = commonsDao.selectProductListByProductId(f_sp_id);
		return productList;
	}
	public List<SysProductVo> selectProductListByContentId(int f_cc_id) {
		List<SysProductVo> productList = commonsDao.selectProductListByContentId(f_cc_id);
		return productList;
	}
	public List<PmsOrgVo> selectOrgCodeByProductId(int f_sp_id) {
		List<PmsOrgVo> orgList = commonsDao.selectOrgCodeByProductId(f_sp_id);
		return orgList;
	}
	
	public UserHistoryVo selectHistory(UserHistoryVo uhv) {
		UserHistoryVo results = commonsDao.selectHistory(uhv);
		return results;
	}
	
	public List<UserHistoryVo> selectHistoryListByContent(UserHistoryVo uhv,int pageNo, int pageSize) {
		List<UserHistoryVo> uhvList = commonsDao.selectHistoryListByContent(uhv,pageNo,pageSize);
		return uhvList;
	}
	
	public List<UserHistoryVo> selectHistoryListByMultirate(UserHistoryVo uhv,int pageNo, int pageSize) {
		List<UserHistoryVo> uhvList = commonsDao.selectHistoryListByMultirate(uhv,pageNo,pageSize);
		return uhvList;
	}
	
	public int insertHistory(UserHistoryVo uhv) {
		int flag = 0;
		if(uhv==null) {
			flag = -1;
		}
		if(flag ==0) {
			return commonsDao.insertHistory(uhv);
		}
		return flag;
	}
	
	public int updateHistory(UserHistoryVo uhv) {
		int flag = 0;
		if(uhv==null) {
			flag = -1;
		}
		if(flag ==0) {
			flag = commonsDao.updateHistory(uhv);
		}
		return flag;
	}
	public int updateHistoryTime(UserHistoryTimeVo uht,String focusIdwai) {
		UserHistoryVo uh = new UserHistoryVo();
		uh.setF_uvh_serverid(uht.getF_uvht_serverid());
		uh.setF_uvh_contentid(uht.getF_uvht_contentid());
		uh.setF_uvh_seriesid(uht.getF_uvht_seriesid());
		uh.setF_uvh_type(uht.getF_uvht_type());
		uh.setF_uvh_catalogid(uht.getF_uvht_catalogid());
		uh.setF_uvh_code(uht.getF_uvht_code());
		uh.setF_uvh_playtime(uht.getF_uvht_playtime());
		UserHistoryVo uhv= this.selectHistory(uh);
		int flag;
		if(uhv!=null){
			flag = this.updateHistory(uh);
		}else{
			flag = this.insertHistory(uh);
		}
		if(flag>0){
			if(focusIdwai.indexOf("_K12_")>-1){
				uht.setF_uvht_comment("K12");
				UserHistoryTimeVo uhtv= commonsDao.selectHistoryTime(uht);
				if(uhtv!=null){
					Date time = uhtv.getF_uvht_cdate();
					try {
						//判断是否是今天
						SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
						if(fmt.format(time).toString().equals(fmt.format(new Date()).toString())){
							//是今天，播放时长累加
							String timecode=uhtv.getF_uvht_playtime();
							String timecode2=uht.getF_uvht_playtime();
							uht.setF_uvht_playtime(String.valueOf(Long.valueOf(timecode)+Long.valueOf(timecode2)));
							uht.setF_uvht_id(uhtv.getF_uvht_id());
							flag = commonsDao.updateHistoryTime(uht);
						}else{
							//不是今天,插入今天观看记录
							flag = commonsDao.insertHistoryTime(uht);
							return flag;
						}
					}catch (Exception e){
						LOG.debug("播放时长累加失败：");
					}
				}else{
					flag = commonsDao.insertHistoryTime(uht);
				}
			}
		}
		return flag;
	}
	
	public List<UserHistoryTimeVo> selectHistoryTime(String f_uvht_serverid,int f_uvht_catalogid,int f_uvht_contentid,Integer f_uvht_type,String beginDate,String endDate,Long seconds){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("f_uvht_serverid", f_uvht_serverid);
		map.put("f_uvht_catalogid", f_uvht_catalogid);
		map.put("f_uvht_contentid", f_uvht_contentid);
		map.put("f_uvht_type", f_uvht_type);
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		map.put("f_uvht_comment", "K12");
		List<UserHistoryTimeVo> list=commonsDao.selectHistoryTimeByDate(map);
		return list;
	}
	
	public String selectAreaIdByServerId(String serverid) {
		return commonsDao.selectAreaIdByServerId(serverid);
	}
	
	public SysProductVo selectProductByAreaId(String areaId,String serviceType) {
		return commonsDao.selectProductByAreaId(areaId,serviceType);
	}
	
	/**
	 * 单次鉴权
	 * @param userID				用户账号
	 * @param productVo				产品包
	 * @param contentID				业务类型或媒资code
	 * @param request
	 * @param response
	 * @return map{
	 * 				Result:鉴权结果
	 * 				authFlag:描述
	 * 				productCode:产品code 对应表sys_product——f_sp_productcode字段
	 * 				productType:产品类型 对应表sys_product——f_sp_type字段
	 * 				productId:产品id 对应表sys_product——f_sp_id字段
	 * 				SPID:企业spid 对应表pms_org——f_po_code字段
	 * 				}
	 */
	public Map<String, String> getAuthResultMap(SysProductVo productVo,String userID,String contentID,HttpServletRequest request,HttpServletResponse response) {
		String Result = "504";
		Map<String, String> map=new HashMap<String, String>();
		if(productVo == null) {//不存在数据
			map.put("Result", "-1");
			map.put("authFlag", "查询无此产品包，异常！");
		}else{
			SysProductVo authProductVo = selectProductByParentId(productVo.getF_sp_id());
			if(authProductVo != null){
				Integer readTimeOut = 99999;
				Integer connectTimeout = 99999;
				
				AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
				if(authProductVo.getF_sp_type()==10) { //10代表为服务ID
					Result= authenticatedService.getServiceAuthenticatedResultByContentID(userID,authProductVo.getF_sp_productcode(),contentID,readTimeOut,connectTimeout);
				} else { //其他为产品IDauthProductVo
					Result= authenticatedService.getProductAuthenticatedResultByContentID(userID,authProductVo.getF_sp_productcode(),contentID,readTimeOut,connectTimeout);
				}
			}else{
				Integer readTimeOut = 99999;
				Integer connectTimeout = 99999;
				
				AuthenticatedService authenticatedService = new AuthenticatedService(request,response);
				if(productVo.getF_sp_type()==10) { //10代表为服务ID
					Result= authenticatedService.getServiceAuthenticatedResultByContentID(userID,productVo.getF_sp_productcode(),contentID,readTimeOut,connectTimeout);
				} else { //其他为产品IDauthProductVo
					Result= authenticatedService.getProductAuthenticatedResultByContentID(userID,productVo.getF_sp_productcode(),contentID,readTimeOut,connectTimeout);
				}
			}
			
			if(Result=="0"||Result.equals("0")) {
				map.put("authFlag", "true");
			}else if(Result=="504"||Result.equals("504")) {
				map.put("authFlag", "false");
			}else{
				map.put("authFlag", "鉴权异常！");
			}
			
			List<PmsOrgVo> orgList = selectOrgCodeByProductId(productVo.getF_sp_id());
			String SPID="";
			if(orgList!=null && orgList.size() > 0){
				SPID=orgList.get(0).getF_po_code();
			}
			if(SPID ==""||"".equals(SPID)){
				SPID="120000";
			}
			map.put("Result", Result);
			map.put("productCode", productVo.getF_sp_productcode());
			map.put("productType", productVo.getF_sp_type()+"");
			map.put("productId", productVo.getF_sp_id()+"");
			map.put("SPID", SPID);
		}
		return map;
	}
	
	public int selectOnDemandCount(UserHistoryVo uhv){
		return commonsDao.selectOnDemandCount(uhv);
	}
	
	public Map<String,Object> selectDatabaseRuntime(){
		return commonsDao.selectDatabaseRuntime();
	}

	public List<SysProductVo> selectProductList(SysProductVo sysProductVo){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_sp_parentid",sysProductVo.getF_sp_parentid());
		map.put("f_spo_orgid",sysProductVo.getF_spo_orgid());
		return commonsDao.selectProductList(map);
	}

	public void analysisOfAdvertisingTimes(HttpServletRequest req, String wma, String adsp, int f_ca_id, int f_cas_id){
		String hotel_gg_maxSumCount = RedisUtils.getString("ADVERTISE_DATA","hotel_gg_maxSumCount_"+f_ca_id+"_"+f_cas_id);
		if(hotel_gg_maxSumCount!=null&&!"".equals(hotel_gg_maxSumCount)&&!"0".equals(hotel_gg_maxSumCount)){ //redis已存最大次数
			int hotel_gg_maxSumCount_int = Integer.parseInt(hotel_gg_maxSumCount);
			String hotel_gg_nowCount = "";
			if (adsp.equals("2")) {
				hotel_gg_nowCount= RedisUtils.getString("ADVERTISE_DATA","hotel_pb_nowCount_"+f_ca_id+"_"+f_cas_id);
			} else {
				hotel_gg_nowCount= RedisUtils.getString("ADVERTISE_DATA","hotel_gg_nowCount_"+f_ca_id+"_"+f_cas_id);
			}
			//String hotel_gg_nowCount= RedisUtils.getString("ADVERTISE_DATA","hotel_gg_nowCount_"+f_ca_id+"_"+f_cas_id);
			int hotel_gg_nowCount_int = 0;
			if (hotel_gg_nowCount!=null&&!"".equals(hotel_gg_nowCount)){
				hotel_gg_nowCount_int = Integer.parseInt(hotel_gg_nowCount);
			}
			hotel_gg_nowCount_int++;
			LOG.debug("总次数上限："+hotel_gg_maxSumCount_int);
			LOG.debug("总观看次数："+hotel_gg_nowCount_int);
			if(hotel_gg_nowCount_int>=hotel_gg_maxSumCount_int){//大于等于最大次数了 把策略改为结束状态（因为广告可能会有多个策略）
				CmAdvertiseVo cmAdvertiseVo = new CmAdvertiseVo();
				cmAdvertiseVo.setF_cas_id(f_cas_id);
				cmAdvertiseVo.setF_cas_status(4);
				hotelDao.updateAdvertiseStrategyStatus(cmAdvertiseVo);
			}else{
				//重新设置当前展示次数
				if (adsp.equals("2")) {
					RedisUtils.setString("ADVERTISE_DATA","hotel_pb_nowCount_"+f_ca_id+"_"+f_cas_id,hotel_gg_nowCount_int+"");//总的
				} else {
					RedisUtils.setString("ADVERTISE_DATA","hotel_gg_nowCount_"+f_ca_id+"_"+f_cas_id,hotel_gg_nowCount_int+"");//总的
				}

				//个人最大次数 记录用户观看次数
				String hotel_gg_maxUserCount = RedisUtils.getString("ADVERTISE_DATA","hotel_gg_maxUserCount_"+f_ca_id+"_"+f_cas_id);
				if(hotel_gg_maxUserCount!=null&&!"".equals(hotel_gg_maxUserCount)&&!"0".equals(hotel_gg_maxUserCount)){
					int hotel_gg_maxUserCount_int = Integer.parseInt(hotel_gg_maxUserCount);
					String hotel_gg_userCount = RedisUtils.getString("ADVERTISE_DATA","hotel_gg_userCount_"+f_ca_id+"_"+f_cas_id+"_"+wma);
					int hotel_gg_userCount_int = 0;
					if (hotel_gg_userCount!=null&&!"".equals(hotel_gg_userCount)){
						hotel_gg_userCount_int = Integer.parseInt(hotel_gg_userCount);
					}
					hotel_gg_userCount_int++;
					LOG.debug("个人次数上限："+hotel_gg_maxUserCount_int);
					LOG.debug("个人观看次数："+hotel_gg_userCount_int);
					RedisUtils.setString("ADVERTISE_DATA","hotel_gg_userCount_"+f_ca_id+"_"+f_cas_id+"_"+wma,hotel_gg_userCount_int+"");
				}
			}
		}
		LOG.debug("开始查询广告");
		CmAdvertiseVo cmAdvertiseVo = new CmAdvertiseVo();
		cmAdvertiseVo.setF_ca_id(f_ca_id);
		List<CmAdvertiseVo> cmAdvertiseVoList = hotelDao.selectHotelAdvertiseById(cmAdvertiseVo);
		cmAdvertiseVo.setF_cas_id(f_cas_id);
		List<CmAdvertiseVo> cmAdvertiseStrategyVoList = hotelDao.selectHotelAdvertiseStrategyById(cmAdvertiseVo);
		LOG.debug("结束查询广告");
		try{
			if (cmAdvertiseVoList.size() > 0) {
				CmAdvertiseLogVo cmAdvertiseLogVo = new CmAdvertiseLogVo();
				cmAdvertiseLogVo.setF_cal_uuid("");
				PmsOrgVo pmsOrgVo = (PmsOrgVo) req.getSession().getAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
				cmAdvertiseLogVo.setF_cal_hotel_contract(pmsOrgVo.getF_po_hotelcontract());
				cmAdvertiseLogVo.setF_cal_mac("");
				cmAdvertiseLogVo.setF_cal_room_num(wma);
				cmAdvertiseLogVo.setF_cal_isoffline(0);
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String ss=sf.format(new Date());
				cmAdvertiseLogVo.setF_cal_server_time(ss);
				cmAdvertiseLogVo.setF_cal_elapsed_real_time(0);
				long justNow =System.currentTimeMillis();
				cmAdvertiseLogVo.setF_cal_record_real_time(justNow);
				cmAdvertiseLogVo.setF_cal_order_number(cmAdvertiseVoList.get(0).getF_ca_order_number());
				cmAdvertiseLogVo.setF_cal_record_time(ss);
				cmAdvertiseLogVo.setF_cal_order_type(cmAdvertiseVoList.get(0).getF_ca_order_type());
				cmAdvertiseLogVo.setF_cal_show_type(1);
				cmAdvertiseLogVo.setF_cal_data_type(0);
				cmAdvertiseLogVo.setF_cal_is_reach(0);
				cmAdvertiseLogVo.setF_cal_client_ip(IpUtil.getIpAddress(req));
				LOG.debug("判断广告是什么类型");
				if (cmAdvertiseVoList.get(0).getF_ca_position_desc() == 1) {
					cmAdvertiseLogVo.setF_cal_adv_scene_name("VA");
					cmAdvertiseLogVo.setF_cal_adv_name("PVA");
					cmAdvertiseLogVo.setF_cal_item_name("V1");
					LOG.debug("视频保存开始"+wma);
					hotelDao.insertHotelAdvertiseLog(cmAdvertiseLogVo);
					LOG.debug("视频保存结束"+wma);
				} else if (cmAdvertiseVoList.get(0).getF_ca_position_desc() == 2) {
					cmAdvertiseLogVo.setF_cal_adv_scene_name("IA");
					cmAdvertiseLogVo.setF_cal_adv_name("PIA");
					cmAdvertiseLogVo.setF_cal_item_name("P1");
					LOG.debug("图片保存开始"+wma);
					hotelDao.insertHotelAdvertiseLog(cmAdvertiseLogVo);
					LOG.debug("图片保存结束"+wma);
				} else if (cmAdvertiseVoList.get(0).getF_ca_position_desc() == 3) {
					String hotel_gg_nowCount = RedisUtils.getString("ADVERTISE_DATA","hotel_gg_nowCount_"+f_ca_id+"_"+f_cas_id);
					LOG.debug("图片现在次数"+Integer.parseInt(hotel_gg_nowCount)+"上限次数"+cmAdvertiseStrategyVoList.get(0).getF_cas_tpCount());
					if (Integer.parseInt(hotel_gg_nowCount) > cmAdvertiseStrategyVoList.get(0).getF_cas_tpCount()) {

					} else {
						cmAdvertiseLogVo.setF_cal_adv_scene_name("IA");
						cmAdvertiseLogVo.setF_cal_adv_name("PIA");
						cmAdvertiseLogVo.setF_cal_item_name("P1");
						LOG.debug("开机图片保存开始"+wma);
						hotelDao.insertHotelAdvertiseLog(cmAdvertiseLogVo);
						LOG.debug("开机图片保存结束"+wma);
					}
					LOG.debug("视频现在次数"+Integer.parseInt(hotel_gg_nowCount)+"上限次数"+cmAdvertiseStrategyVoList.get(0).getF_cas_spCount());
					if (Integer.parseInt(hotel_gg_nowCount) > cmAdvertiseStrategyVoList.get(0).getF_cas_spCount()) {

					} else {
						cmAdvertiseLogVo.setF_cal_adv_scene_name("VA");
						cmAdvertiseLogVo.setF_cal_adv_name("PVA");
						cmAdvertiseLogVo.setF_cal_item_name("V1");
						LOG.debug("开机视频保存开始"+wma);
						hotelDao.insertHotelAdvertiseLog(cmAdvertiseLogVo);
						LOG.debug("开机视频保存结束"+wma);
					}
				} else if (cmAdvertiseVoList.get(0).getF_ca_position_desc() == 4) {
					cmAdvertiseLogVo.setF_cal_adv_scene_name("SSI");
					cmAdvertiseLogVo.setF_cal_adv_name("SSI");
					cmAdvertiseLogVo.setF_cal_item_name("P1");
					LOG.debug("屏保保存开始"+wma);
					hotelDao.insertHotelAdvertiseLog(cmAdvertiseLogVo);
					LOG.debug("屏保保存结束"+wma);
				}
			} else {
				LOG.debug("播放未查到广告"+f_ca_id);
			}
		}catch (Exception e){
			LOG.debug("错误"+f_ca_id);
		}

	}
}
